<?php
/**
 * Description: 引导评论的赠送课程
 * User: devforma
 * Date: 15/7/23
 * Time: 15:05
 */

class GetRateCourse implements iController {
    private $specialCourses = [1599, 1596];

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (!empty($queryArgs['action']) && $queryArgs['action'] === 'getCourse') {
            $sql = "SELECT id, course_name, price FROM `data_live_course` WHERE `is_rate_gift`=1 AND `publish_status`='publish'";
            $courses = $cmsdb->getResults($sql);

            $course = $courses[array_rand($courses, 1)];

            return genOutput(1, array(
                'course_id' => intval($course->id),
                'course_name' => $course->course_name,
                'course_price' => floatval($course->price)
            ));
        } elseif (!empty($queryArgs['action']) && $queryArgs['action'] === 'enroll' && !empty($queryArgs['course_id'])) {

            if (validateUser($queryArgs) !== 1)
                return genOutput(1000);

            $exists = $cmsdb->getVar("SELECT `id` FROM `data_live_course` WHERE `is_rate_gift`=1 AND `publish_status`='publish' AND `id`=:cid",
                array(':cid' => $queryArgs['course_id']));

            if (!in_array($queryArgs['course_id'], $this->specialCourses) && empty($exists))
                return genOutput(1001);

            $enrolled = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id`=:cid AND `product_type`="zhiboke" LIMIT 1',
                array(':uid' => $queryArgs['user_id'], ':cid' => $queryArgs['course_id']));
            if (!$enrolled) {
                $cmsdb->insert('relation_user_product', array(
                    'user_id' => $queryArgs['user_id'],
                    'product_id' => $queryArgs['course_id'],
                    'order_id' => 0,
                    'order_time' => date('y-m-d H:i:s'),
                    'product_type' => 'zhiboke',
                    'channel' => 3 //标记开通类型为评价开通
                ));

                //更新购课人数缓存
                updateCoursePurchasedPersons($queryArgs['course_id'], 1);
            }

            return genOutput(1, array(
                'jump_url' => YG_MOBILE_SECURE_URL . '/index.html#/live/purchased?course_id='.$queryArgs['course_id']
            ));
        }

        return genOutput(1000);
    }
}